﻿using System;

namespace Facebook
{
    public struct UnixDateTime
    {
        private const Int64 DIFF = 621355968000000000;
        private const Int64 MULTIPLIER = 10000000;

        public UnixDateTime(Int64 unixTime)
            : this()
        {
            this.Value = unixTime;
        }

        public UnixDateTime(DateTime dateTime)
            : this()
        {
            this.Value = dateTime.Ticks / MULTIPLIER - DIFF;
        }

        public Int64 Value { get; set; }

        public DateTime ToDateTime()
        {
            return UnixDateTime.ToDateTime(this.Value);
        }

        public static DateTime ToDateTime(Int64 unixTime)
        {
            if (unixTime == 0) return DateTime.MinValue;
            else return new DateTime(unixTime * MULTIPLIER + DIFF, DateTimeKind.Utc);
        }        

        public static Boolean TryParse(String input, out UnixDateTime unixDateTime)
        {
            Int64 value;
            if (Int64.TryParse(input, out value))
            {
                unixDateTime = new UnixDateTime(value);
                return true;
            }
            else
            {
                unixDateTime = new UnixDateTime(0);
                return false;
            }
        }
    }
}